<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="类别名称" prop="categoryName">
        <el-input
          v-model="queryParams.categoryName"
          placeholder="请输入类别名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="类别归属" prop="categoryOwner">
        <el-select
          v-model="queryParams.categoryOwner"
          placeholder="请选择类别归属"
          clearable
        >
          <el-option
            v-for="dict in dict.type.category_owner"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['basicData:categoryManagement:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-sort"
          size="mini"
          @click="toggleExpandAll"
          >展开/折叠</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="categoryManagementList"
      row-key="categoryId"
      :default-expand-all="isExpandAll"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column label="类别名称" align="center" prop="categoryName" />
      <el-table-column label="类别归属" align="center" prop="categoryOwner">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.category_owner"
            :value="scope.row.categoryOwner"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['basicData:categoryManagement:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
            v-hasPermi="['basicData:categoryManagement:add']"
            >新增</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['basicData:categoryManagement:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改分类管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="上级分类" prop="parentId">
              <treeselect
                v-model="form.parentId"
                :options="categoryOptions"
                :normalizer="normalizer"
                :show-count="true"
                placeholder="选择上级菜单"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="类别名称" prop="categoryName">
              <el-input
                v-model="form.categoryName"
                placeholder="请输入类别名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="类别归属" prop="categoryOwner">
              <el-select
                filterable
                clearable
                v-model="form.categoryOwner"
                placeholder="请选择类别归属"
              >
                <el-option
                  v-for="dict in dict.type.category_owner"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listCategoryManagement,
  getCategoryManagement,
  delCategoryManagement,
  addCategoryManagement,
  updateCategoryManagement,
} from '@/api/basicData/categoryManagement/categoryManagement.js'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'

export default {
  name: 'CategoryManagement',
  dicts: ['category_owner'],
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 分类管理表格数据
      categoryManagementList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        categoryName: null,
        categoryOwner: null,
      },
      // 分类树选项
      categoryOptions: [],
      // 是否展开，默认全部折叠
      isExpandAll: false,
      // 重新渲染表格状态
      refreshTable: true,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        categoryName: [
          { required: true, message: '类别名称不能为空', trigger: 'blur' },
        ],
        categoryOwner: [
          {
            required: true,
            message: '类别归属(01=供应商,02=客户,03=产品)不能为空',
            trigger: 'change',
          },
        ],
      },
    }
  },
  created() {
    this.getList()
  },
  watch: {
    'form.parentId': {
      handler(newVal, oldVal) {
        if (newVal && newVal !== 0) {
          //在this.categoryManagementList中查找节点，并获取节点的categoryOwner
          let categoryOwner = (
            this.categoryManagementList.find(
              (item) => item.categoryId === newVal
            ) || {}
          ).categoryOwner
          if (categoryOwner) {
            this.form.categoryOwner = categoryOwner
          }
        } else {
          this.form.categoryOwner = null
        }
      },
    },
  },
  methods: {
    /** 查询分类管理列表 */
    getList() {
      this.loading = true
      listCategoryManagement(this.queryParams).then((response) => {
        this.categoryManagementList = this.handleTree(
          response.data,
          'categoryId'
        )
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        categoryId: null,
        categoryName: null,
        parentId: null,
        categoryOwner: null,
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset()
      this.getTreeselect()
      if (row != null && row.categoryId) {
        this.form.parentId = row.categoryId
      } else {
        this.form.parentId = 0
      }
      this.open = true
      this.title = '添加类别'
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false
      this.isExpandAll = !this.isExpandAll
      this.$nextTick(() => {
        this.refreshTable = true
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      this.getTreeselect()
      getCategoryManagement(row.categoryId).then((response) => {
        this.form = response.data
        this.open = true
        this.title = '修改类别'
      })
    },
    getTreeselect() {
      listCategoryManagement().then((response) => {
        this.categoryOptions = []
        const category = { categoryId: 0, categoryName: '主类目', children: [] }
        category.children = this.handleTree(response.data || {}, 'categoryId')

        this.categoryOptions.push(category)
      })
    },
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.categoryId,
        label: node.categoryName,
        children: node.children,
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.form.categoryId != null) {
            updateCategoryManagement(this.form).then((response) => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addCategoryManagement(this.form).then((response) => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const categoryIds = row.categoryId || this.ids
      this.$modal
        .confirm('是否确认删除类别名称为"' + row.categoryName + '"的数据项？')
        .then(function () {
          return delCategoryManagement(categoryIds)
        })
        .then(() => {
          this.getList()
          this.$modal.msgSuccess('删除成功')
        })
        .catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        'basicData/categoryManagement/export',
        {
          ...this.queryParams,
        },
        `categoryManagement_${new Date().getTime()}.xlsx`
      )
    },
  },
}
</script>
